package cn.onein.edu.backend.dao;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.SqlMapClientTemplate;

import cn.onein.edu.backend.vo.DailyAcitonMailVO;
import cn.onein.edu.biz.bean.ActionCategory;
import cn.onein.edu.biz.bean.DailyAction;
import cn.onein.edu.biz.bean.User;
import cn.onein.edu.biz.bean.UserAction;
import cn.onein.edu.common.ActionResultType;
import cn.onein.edu.util.DateUtil;

import com.ibatis.sqlmap.client.SqlMapExecutor;

/**
 * 用户每日行动指南数据处理DAO
 * @author Upton
 *
 */
public class DailyUserActionsDao {
	Logger logger = Logger.getLogger(DailyUserActionsDao.class);
	
	//插入下一条行动指南数据的长度周期，6即为下一周
	public static final int NEXT_ACTIONS_INSERT_PERIOD = 6;
	
	private SqlMapClientTemplate sqlMapClientTemplate;
	
	public void setSqlMapClientTemplate(SqlMapClientTemplate sqlMapClientTemplate){
		this.sqlMapClientTemplate = sqlMapClientTemplate;
	}
	
	/**
	 * 初始化
	 */
	public void initUserShadow(){
		sqlMapClientTemplate.update("initUserShadow");
	}
	
	/**
	 * 取得未处理用户列表
	 * @param maxPerTa
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<User> getUnCompletedUserList(Integer maxPerTa){		
		return (List<User>)sqlMapClientTemplate.queryForList("getUnCompletedUserList", maxPerTa);
	}

	/**
	 * 1.更新用户当天的Action Category信息
	 * 2.Insert 7天后的 UserAction数据，还要判断当天的ActionCategory是否要变更
	 * @param list
	 * @return
	 */
	public List<User> doDailyUserActions(final List<User> list){
		List<User> resultList = sqlMapClientTemplate.execute(new SqlMapClientCallback<List<User>>(){
			@Override
			public List<User> doInSqlMapClient(SqlMapExecutor executor)throws SQLException {
				executor.startBatch();				
				for(User user : list){
					Date birthday = user.getBirthday();
					
					Calendar nextWeekCal = Calendar.getInstance(); 
					nextWeekCal.setTime(new Date());					
					nextWeekCal.add(Calendar.DAY_OF_MONTH, NEXT_ACTIONS_INSERT_PERIOD);
					
					Date nextWeekDate = nextWeekCal.getTime();
					Integer nextWeekAge = DateUtil.birthday2Age(birthday,nextWeekDate);
					
					//查询下周的用户行动指南分类属性，目前暂时只根据年龄来区分
					ActionCategory categoryNextWeek = (ActionCategory)executor.queryForObject("getCategoryByAge", nextWeekAge);
					if(categoryNextWeek != null){
						//取得Actionindex
						Integer actionIndex = DateUtil.calcActionIndexByBirthday(birthday, nextWeekDate);
						
						DailyAction dailyAction = new DailyAction();
						dailyAction.setActionCatId(categoryNextWeek.getId());
						dailyAction.setVersion(categoryNextWeek.getCurrVersion());
						dailyAction.setActionIndex(actionIndex);
						
						//取得要Insert的DailyAction
						dailyAction = (DailyAction)executor.queryForObject("getDailyActionByCategory", dailyAction);
						if(dailyAction != null){
							//插入nextWeekDate的数据到UserActions表
							UserAction userAction = new UserAction();
							Date expiresDate = user.getLevelExpires();
							boolean active = false;
							
							//会员资格是否有效
							if(expiresDate != null){
								SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
								try {
									nextWeekDate = format.parse(format.format(nextWeekDate));
									
									if(!expiresDate.before(nextWeekDate)){
										active = true;
									}
								} catch (ParseException e) {
									logger.error("Pasre date error.", e);
								}
							}
							
							userAction.setUserId(user.getId());
							userAction.setActionDate(nextWeekDate);
							userAction.setActive(active);
							userAction.setDailyActionId(dailyAction.getId());
							userAction.setActionResult(ActionResultType.NeverDone.ordinal());
							
							executor.insert("insertUserActions", userAction);
						}
					}
					
					//目前不用考虑更新用户的category 属性，直接根据用户字段值去取Category ID值
					//更新今天的用户属性
					//查询今天的用户行动指南分类属性，目前暂时只根据年龄来区分
					//Integer todayAge = DateUtil.birthday2Age(birthday);
					//ActionCategory categoryToday = (ActionCategory)executor.queryForObject("getCategoryByAge", todayAge);
					
					//if(categoryToday != null && user.getActionCategoryId() != categoryToday.getId()){
					//	user.setActionCategoryId(categoryToday.getId());
					//	executor.update("updateUserActionCategoryProp", user);
					//}					
				}
				
				executor.executeBatch();
				return list;
			}});
		
		return resultList;
	}
	
	/**
	 * 更新指定的UserShadow的Completed = true
	 * @param list
	 */
	public void setUserShadowCompleted(final List<User> list){
		StringBuffer userIds = new StringBuffer().append(list.get(0).getId());
		
		int size = list.size();
		for(int i = 1; i < size; i++){
			userIds.append(",").append(list.get(i).getId());
		}
		
		sqlMapClientTemplate.update("setUserShadowCompleted",userIds.toString());
	}
	
	/**
	 * 根据用户ID和日期查找指定每日指南
	 * @param userid
	 * @param date
	 * @return
	 */
	public UserAction getUserActionByUQKey(Long userid, Date date){
		Map<String,Object> param = new HashMap<String,Object>();
		
		param.put("userid", userid);
		param.put("actionDate", DateUtil.formatDate4Query(date));
		
		return (UserAction)sqlMapClientTemplate.queryForObject("getUserActionByUQKey", param);
	}
	
	/**
	 * 根基ID查询DailyAction
	 * @param id
	 * @return
	 */
	public DailyAcitonMailVO getDailyActionById(Long id){
		return (DailyAcitonMailVO)sqlMapClientTemplate.queryForObject("getDailyActionById", id);
	}
}
